/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.open.api.core.service.processor.base.pre;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.business.customer.facade.info.partner.PartnerInfo;
import info.peigen.hotpot.common.core.util.IdUtil;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.component.open.api.core.service.processor.base.AbstractOpenApiServiceProcessor;
import info.peigen.hotpot.component.open.api.facade.Api;
import info.peigen.hotpot.component.open.api.facade.order.OpenApiOrder;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessor;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessorServiceContext;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.TranAnno;
import org.noear.solon.data.tran.TranPolicy;
import org.noear.solon.data.tran.TranUtils;

import static org.noear.solon.data.tran.TranIsolation.read_committed;

/**
 * <b>(OpenApiRequestNoUniqueVerifyProcessor)</b>
 * 校验RequestNo是否唯一,同时存储本次调用记录
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/6/13
 */
@SuppressWarnings("rawtypes")
@Component
public class OpenApiRequestNoUniqueVerifyProcessor extends AbstractOpenApiServiceProcessor implements OpenApiProcessor {
    @Override
    public Integer level() {
        return 4;
    }

    @Override
    public void execute(OpenApiProcessorServiceContext serviceContext) {
        OpenApiOrder order       = serviceContext.getOrder();
        PartnerInfo  partnerInfo = (PartnerInfo) serviceContext.getPartnerInfo();
        Api          api         = BeanUtil.copyProperties(order, Api.class).setGid(IdUtil.gid());
        // 验证当前requestNo是否包含partner专属Abbreviation，以避免重复
        Assert.isTrue(StrUtil.equals(StrUtil.subWithLength(api.getRequestNo(), 14, 8), partnerInfo.getAbbreviation()), "requestNo未包含[合作伙伴标记码]");

        try {
            TranUtils.execute(new TranAnno().isolation(read_committed).policy(TranPolicy.required),
                    () -> {
                        openApiLogRepository.store(api);
                    });
        } catch (Throwable e) {
            e.printStackTrace();
            throw new BusinessException("requestNo重复[requestNo=]" + api.getRequestNo());
        }
    }
}